<?php

// [ 请求类 ]

namespace core;

class Request
{
    private static $_request = [
        // 请求协议
        'protocol'   => '',
        // 请求头
        'header'     => [],
        // 请求方法
        'method'     => '',
        // 客户端ip
        'ip'         => '',
        // 请求域名
        'domain'     => '',
        // 请求端口
        'port'       => 0,
        // 请求参数
        'param'      => [],
    ];

    public static function init()
    {
        self::$_request['protocol'] = $_SERVER['SERVER_PROTOCOL'];

        self::$_request['method'] = $_SERVER['REQUEST_METHOD'];

        foreach ($_SERVER as $name => $value) {
            if (substr($name,0,5) == 'HTTP_') {
                self::$_request['header'][str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($name, 5))))] = $value;
            }
        }

        self::$_request['ip'] = get_client_ip();

        self::$_request['domain'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'];

        self::$_request['port'] = $_SERVER['SERVER_PORT'];

        switch (self::$_request['method']) {
            case 'GET':
                self::$_request['param'] = $_GET;
                break;
            case 'POST':
                self::$_request['param'] = $_POST;
                break;
            case 'PUT':
                parse_str(file_get_contents('php://input'),self::$_request['param']);
                break;
            case 'DELETE':
                parse_str(file_get_contents('php://input'),self::$_request['param']);
                break;
            default:
                self::$_request['param'] = [];
                break;
        }
    }

    public static function get($name = '')
    {
        if ( empty($name) ) {
            return self::$_request;
        } else {
            if ( strpos($name, '.') ) {
                $arr = explode('.', $name);
                $request = self::$_request;
                foreach ($arr as $v) {
                    $request = isset($request[$v]) ? $request = $request[$v] : false;
                    if (!$request) break;
                }
                return $request;
            } else {
                return isset( self::$_request[$name] ) ? self::$_request[$name] : false;
            }
        }
    }

    public static function set($name, $value)
    {
        self::$_request[$name] = $value;
    }
}
